/*
 * @Author: chengsl
 * @Date: 2021-12-21 14:32:56
 * @LastEditors: chengsl
 * @LastEditTime: 2023-05-09 14:53:10
 * @Description: file content
 */
import router from './routers'
import store from '@/store'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })

import Config from '@/settings'
import path from 'path'

router.beforeEach((to, from, next) => {
  // 非 qiankun 环境下执行
  if (!window.__POWERED_BY_QIANKUN__ && !localStorage.getItem('appName')) {
    NProgress.start() // 进度条开始
    if (to.meta.title) {
      document.title = to.meta.title + ' - ' + Config.title // 设置页面的标题
    }
    /* 异步路由注册 */
    const hasAsyncRouters =
      store.getters.addRouters && store.getters.addRouters.length
    if (hasAsyncRouters) {
      next()
    } else {
      initAsyncRouters(next, to)
    }
  } else {
    // qiankun 环境下这啥也不用干; qiankun环境下路由实例创建的逻辑在mian.js里面，狗兔there去康康
  }
})

router.afterEach(() => {
  NProgress.done()
})

import Layout from '@/layout/index'
export const loadView = (view) => {
  return () => import(`@/views/${view}`)
}

// 根据以上代码，发现该代码只在非qiankun环境下执行
function filterRouters(routers, basePath = '/', parent = null) {
  return routers.filter(item => {
    const routerPath = path.resolve(basePath, item.path)
    if (!['Layout', 'ParentView'].includes(item.component)) {
      if (item.component) {
        item.component = loadView(item.component)
      }
      if (item.iframeComponent) {
        item.iframeComponent = loadView(item.iframeComponent)
      }
      if (!parent && !item.children) {
        router.addRoute(item) // 不需要包裹layout组件的页面
      } else {
        router.addRoute(
          {
            path: '/',
            component: Layout,
            children: [{ ...item, path: routerPath }]
          }
        )
      }
    }
    if (item.children && item.children.length) {
      filterRouters(item.children, routerPath, item)
    }
    return true
  })
}

/**
 * @description: 初始化异步路由（前端暂时写死数据）
 */
const initAsyncRouters = async(next, to) => {
  const sdata = JSON.parse(JSON.stringify(asyncRouterTable))
  const rewriteRoutes = filterRouters(sdata)
  await store.dispatch('GenerateRoutes', rewriteRoutes)
  next({ ...to, replace: true })
}

/**
 * @description: 项目的业务路由表
 * @param {*}
 */
export const asyncRouterTable = [
  {
    name: '微应用系统',
    path: '/microapp',
    hidden: false,
    redirect: 'noredirect',
    component: 'Layout',
    alwaysShow: true,
    meta: {
      title: '父层级菜单',
      icon: 'table'
    },
    children: [
      {
        qiankunRouter: true,
        name: 'DemoPage',
        path: 'demoPage',
        hidden: false,
        component: 'demo-page',
        meta: {
          title: '测试页面',
          icon: '',
          noCache: false
        }
      },
      {
        qiankunRouter: true,
        name: 'DemoPage2',
        path: 'demoPage2',
        hidden: false,
        component: 'demo-page2',
        meta: {
          title: '测试页面2',
          icon: '',
          noCache: false
        }
      }
    ]
  }
  
]
